package com.billing.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.billing.model.entity.TUser;
import com.billing.model.entity.UserAppBean;
import com.billing.service.UserService;
import com.billing.utils.MD5Util;

@RequestMapping(value = "/userlogin")
@Controller
public class UserLoginController {

	@Resource
	private UserService userService;


	/**
	 * 用户登陆
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/mobilelogin", method = RequestMethod.POST, produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String mobilelogin(HttpServletRequest request, Model model) {
		String msg=null;
		JSONObject jsonObject = null;
		String loginname =null;
		String password =null;
		String json = request.getParameter("json");
		jsonObject = JSONObject.fromObject(json);
		try{
			loginname =jsonObject.getString("username");
			password =jsonObject.getString("password");
		}catch(Exception e){
            msg="{\"code\":\"9002\",\"msg\":\"参数有误"+e.getMessage().replaceAll("\"", "")+"\"}";
            return msg;
		}
		try {
//			password = MD5Util.md5Encode(password);
			TUser user=userService.getTUser(loginname, password);
			if (user != null) {
				user.setWhetheronline(0);
				user.setLogintime(System.currentTimeMillis());
				byte[] by=(user.getLoginname()+user.getPassword()+user.getLogintime()+user.getWhetheronline()).getBytes();
				String token=MD5Util.digest(by);
				user.setToken(token);
				userService.updateTUser(user);
				UserAppBean userapp=new UserAppBean();
				BeanUtils.copyProperties(userapp, user);
				Map<String, Object> map=new HashMap<String, Object>();
				map.put("data", userapp);
				map.put("code", 1);
				JSONObject jsons = JSONObject.fromObject(map);// 将java对象转换为json对象
				msg = jsons.toString();
			} else {
				msg="{\"code\":\"2\",\"msg\":\"用户名或密码错误\"}";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return msg;
	}
}
